let fs = require("fs")
let pathApi = require("path")
let CNs = {}

let CNPaths = ["./Languages/cn"]   

CNPaths.forEach(path => {
    let ret = fs.readFileSync(path).toString()
    ret = ret.match(/<string id=".+" text="[^"]+"\/>/g);
    ret.forEach( v => {
        if(/<string id="(.+)" text="([^"]+)"\/>/.test(v)){
            CNs[RegExp.$1] = RegExp.$2
        }
    })
})

// console.log(CNs);


let items = {}

let itemPaths = ["./spitems/weapons.xml", "./spitems/arm_armors.xml", "./spitems/body_armors.xml",
    "./spitems/head_armors.xml", "./spitems/horses_and_others.xml", "./spitems/leg_armors.xml",
    "./spitems/shields.xml", "./spitems/shoulder_armors.xml"
]
itemPaths.forEach(path => {
    let ret = fs.readFileSync(path).toString()
    let arr = ret.match(/id="[^"]+"\n?\s+name="{=[^}]+}/g)
    arr.forEach(function(item){
        if(/id="(.+)"\n?\s+name="{=(.+)}$/.test(item)){
            items[`"${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
            items[`"Item.${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
            ret = ret.replace(new RegExp(`"${RegExp.$1}"`,"ig"), `"${CNs[RegExp.$2]}"`)
        }
    })
    if(!fs.existsSync(pathApi.dirname(path) + "cn")){
        fs.mkdirSync(pathApi.dirname(path) + "cn")
    }
    fs.writeFile(pathApi.dirname(path) + "cn/" + pathApi.basename(path), ret, function(err) {
        if(err) {
            return;
        }
    });
})

let charactersPath = ["./bandits.xml", "./spnpccharacters.xml"];
charactersPath.forEach(path => {
    let ret = fs.readFileSync(path).toString()
    for (let key in CNs) {
        ret = ret.replace(new RegExp( `{=${key}}`,"ig"), CNs[key])
    }
    for (let key in items) {
        ret = ret.replace(new RegExp( key,"ig"), items[key])
    }
    if(!fs.existsSync(pathApi.dirname(path) + "/characterCn")){
        fs.mkdirSync(pathApi.dirname(path) + "/characterCn")
    }
    fs.writeFile(pathApi.dirname(path) + "/characterCn/" + pathApi.basename(path), ret, function(err) {
        if(err) {
            return;
        }
    }); 
})